﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TempCtr.Model
{
    class DealData
    {
        public static bool dealData(byte[] RxBuffer)
        {
            try
            {
                if (RxBuffer[0] > 32) 
                {
                    MainFrom.Logger.Error("返回数据地址超范围！");
                    string str = ByteToHexStr(RxBuffer);
                    MainFrom.Logger.Error(str);
                    for (int i = 0; i < 12; i++)
                    {
                        RxBuffer[i] = RxBuffer[i + 1];
                    }
                    MainFrom.Logger.Error("修改后的数据！");
                    str = ByteToHexStr(RxBuffer);
                    MainFrom.Logger.Error(str);
                } 
                if (!ThermostatSerialPort.CRC16In(RxBuffer))
                {
                    MainFrom.Logger.Error("返回数据错误！");
                    string str = ByteToHexStr(RxBuffer);
                    MainFrom.Logger.Error(str);
                    return false;
                }
                var Thermostat_Addr = RxBuffer[0];  //获取包类型
                var Cmd = RxBuffer[1]; //获取命令
                var Data_Length = (Int16)RxBuffer[2];
                int TempData = 0;
                if (Data_Length == 2) TempData = (RxBuffer[3] << 8 | RxBuffer[4]);
                if (Data_Length == 4) TempData = (Int32)(RxBuffer[5] << 24 | RxBuffer[6] << 16 | RxBuffer[3] << 8 | (int)RxBuffer[4]);
                Thermostat.NewDataEvent(Thermostat_Addr, Thermostat_Addr, Cmd, Data_Length, TempData);
                if (ThermostatSerialPort.WaitingReplyList.Contains(Thermostat_Addr))
                {
                    ThermostatSerialPort.WaitingReplyList.Remove(Thermostat_Addr);
                }
               // MainFrom.Logger.Error("返回数据成功！");
                return true;
            }
            catch (Exception ex)
            {
                MainFrom.Logger.Error("返回数据处理错误！"+ex.ToString());
                return false;
            }
        }

        /// <summary>
        /// byte[]转为16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ByteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += (bytes[i].ToString("X2")+" ");
                }
            }
            return returnStr;
        }
    }
}
